package com.zhima.util;

import com.zhima.enums.Judge0RequestParamEnums;

import static com.zhima.properties.Judge0Properties.JUDGE0_URL;

/**
 * @author : Administer
 * @date : 2023-09-07 09:24
 **/
public class RequestUrlBuilder {
    private StringBuilder requestUrl;
    private boolean hasAddRequestParam;
    private boolean hasAddRequestPathVariable;

    private RequestUrlBuilder(String judge0Url) {
        requestUrl = new StringBuilder(judge0Url);
        hasAddRequestParam = false;
        hasAddRequestPathVariable = false;
    }

    public static RequestUrlBuilder builder(String uri) {
        return new RequestUrlBuilder(JUDGE0_URL + uri);
    }

    public RequestUrlBuilder enable(Judge0RequestParamEnums judge0RequestParamEnums) {
        this.addParam(judge0RequestParamEnums, String.valueOf(true));
        return this;
    }

    public RequestUrlBuilder addParam(Judge0RequestParamEnums judge0RequestParamEnums, String value) {
        if (hasAddRequestPathVariable) {
            throw new IllegalArgumentException("请在添加请求参数前添加路径参数");
        }
        if (!hasAddRequestParam) {
            requestUrl.append("?");
            hasAddRequestParam = true;
        } else {
            requestUrl.append("&");
        }
        requestUrl.append(judge0RequestParamEnums.getParamName()).append("=").append(value);
        return this;
    }

    public RequestUrlBuilder addPathVariable(String value) {
        if (hasAddRequestParam) {
            throw new IllegalArgumentException("请在添加请求参数前添加路径参数");
        }
        hasAddRequestPathVariable = true;
        requestUrl.append("/").append(value);
        return this;
    }

    public String build() {
        return requestUrl.toString();
    }
}
